package com.ruoyi.web.controller.workJob;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.validator.ValidatorUtils;
import com.ruoyi.worker.constant.Constant;
import com.ruoyi.worker.domain.*;
import com.ruoyi.worker.handler.TermWorkerExcelVerifyHandlerImpl;
import com.ruoyi.worker.service.ITermWorkerService;
import com.ruoyi.worker.service.TermAttendanceGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.InputStream;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 功能描述：长期工管理
 *
 * @Classname TermWorkerController
 * @Description TODO
 * @Date 2021/11/8 14:41
 * @Created by 刘松山
 */
@RestController
@RequestMapping("/termWorkerApi")
@Slf4j
public class TermWorkerController extends BaseController {
    @Autowired
    private ITermWorkerService termWorkerService;
    @Autowired
    private TermAttendanceGroupService termAttendanceGroupService;

    /**
     * 查询【长期工】列表
     */

    @GetMapping("/list")
    public TableDataInfo list(TermWorker termWorker) {
        startPage();
        List<TermWorker> list = termWorkerService.selectTermWorkerList(termWorker);
        return getDataTable(list);
    }

    @Log(title = "查询长期工在职离职流水", businessType = BusinessType.OTHER)
    @GetMapping("/listTermWorkerLogList")
    public TableDataInfo listTermWorkerLogList(TermWorker termWorker) {
        startPage();
        List<TermWorker> list = termWorkerService.selelctTermWorkerLogList(termWorker.getIdCard());
        return getDataTable(list);
    }


    /**
     * 导出【长期工】列表
     */

    @Log(title = "【导出长期工信息】", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TermWorker termWorker) {
        List<TermWorker> list = termWorkerService.selectTermWorkerList(termWorker);
        ExcelUtil<TermWorker> util = new ExcelUtil<TermWorker>(TermWorker.class);
        return util.exportExcel(list, "长期工数据");
    }

    /**
     * 获取【长期工】详细信息
     */
    @Log(title = "获取【长期工】详细信息", businessType = BusinessType.OTHER)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(termWorkerService.selectTermWorkerById(id));
    }

    /**
     * 新增【长期工】
     */

    @Log(title = "新增【长期工】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TermWorker termWorker) {
        termWorker.setCreateBy(getUsername());
        int flag = termWorkerService.insertTermWorker(termWorker);
        if (flag == -1) {
            return AjaxResult.error("身份证" + termWorker.getIdCard() + "已经存在了,请核对！");
        }
        return toAjax(flag);
    }

    /**
     * 修改【长期工】
     */

    @Log(title = "修改【长期工】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TermWorker termWorker) throws ParseException {
        termWorker.setUpdateBy(getUsername());
        termWorker.setCreateBy(getUsername());
        int flag = termWorkerService.updateTermWorker(termWorker);
        if (flag == -1) {
            return AjaxResult.error("身份证" + termWorker.getIdCard() + "已经存在了,请核对！");
        }
        return toAjax(flag);
    }

    @Log(title = "加入黑名单_长期工", businessType = BusinessType.UPDATE)
    //@DeleteMapping("/updateWorkStatus")
    @PostMapping("/addToBlacklist")
    public AjaxResult addToBlacklist(@Valid @RequestBody RzBlockWorker beau, BindingResult result) {

        if (result.hasErrors()){
            // 没通过校验
            return AjaxResult.error(ValidatorUtils.getValidationMessByBindingResult(result).toString());
        }
        beau.setWorkerType(Constant.WORKER_TYPE_C);
        RzBlockWorker info = termWorkerService.checkBlackFlag(beau);
        if (!Objects.isNull(info)) {
            return AjaxResult.error("该长期工已在黑名单中");
        }
        return toAjax(termWorkerService.updateWorkStatus(beau));
    }

    @Log(title = "批量修改【长期工】离职时间", businessType = BusinessType.UPDATE)
    @DeleteMapping("updateTermWorkerLeaveTime/{ids}")
    public AjaxResult updateTermWorkerLeaveTime(@PathVariable Long[] ids) {

        return toAjax(termWorkerService.updateTermWorkerLeaveTime(ids,getUsername()));
    }

    /**
     * 删除【长期工】
     */

    @Log(title = "删除【长期工】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {

        return toAjax(termWorkerService.deleteTermWorkerByIds(ids));
    }

    /**
     * 功能描述:查询组织结构列表
     *
     * @return com.ruoyi.common.core.page.TableDataInfo
     * @Date 2021/11/8 16:34
     * @author admin
     */
    @GetMapping("/listDept")
    public AjaxResult listDept() {
        Map<String, Object> map = termWorkerService.listDept();
        return AjaxResult.success(map);
    }

    @Log(title = "导入【长期工】", businessType = BusinessType.IMPORT)
    @PostMapping("/importTermWorker_copy")
    public AjaxResult importTermWorker_Copy(MultipartFile file) {
        return success();
        /*{
            List<TermWorkerExcel> excelTermWorkers = null;
            try {
                excelTermWorkers = baseImport(file.getInputStream(), 0, 1, true, TermWorkerExcel.class);
            } catch (Exception e) {
                log.error("长期工信息导入失败:[{}]", e.getMessage(), e);
                throw new CustomException(e.getMessage());
            }
            if (null == excelTermWorkers || excelTermWorkers.size() < 1) {
                return AjaxResult.error("excel长期工信息导入失败，信息为空");
            }

            List<String> errorList = new ArrayList<>();

            for (int i = 0; i < excelTermWorkers.size(); i++) {
                TermWorkerExcel e = excelTermWorkers.get(i);
                if (e.getWorkerName() == null || "".equals(e.getWorkerName())) {
                    errorList.add("第" + (i + 2) + "行中的姓名为空");
                }


                if (e.getIdCard() == null || "".equals(e.getIdCard())) {
                    errorList.add("第" + (i + 2) + "行中的身份证为空");
                }
                e.setIdCard(StringUtils.replaceBlank(e.getIdCard()));
                //校验身份证合法性
                if (!IdcardValidatorUtil.isValidate18Idcard(e.getIdCard())) {
                    errorList.add("第" + (i + 2) + "行中的身份证不合法，请核对");
                } else {
                    Map<String, String> idCardMap = DateUtils.getBirthdayAgeSex(e.getIdCard());
                    if (Integer.parseInt(idCardMap.get("age")) < 20 || Integer.parseInt(idCardMap.get("age")) > 50) {
                        errorList.add("第" + (i + 2) + "行中的年龄不在20-50之间");
                    }
                    e.setAge(Long.parseLong(idCardMap.get("age")));
                    e.setBirthday(idCardMap.get("birthday"));
                    e.setSex(idCardMap.get("sex"));
                }


                if (e.getPhoneCode() == null || "".equals(e.getPhoneCode())) {
                    errorList.add("第" + (i + 2) + "行中的联系电话为空");
                }
                if (e.getWorkStatusName() == null || "".equals(e.getWorkStatusName())) {
                    errorList.add("第" + (i + 2) + "行中的员工状态为空");
                } else if (!e.getWorkStatusName().equals("在职") && !e.getWorkStatusName().equals("离职")) {
                    errorList.add("第" + (i + 2) + "行中的员工状态名称错误");
                }
                if (e.getClazzName() == null || "".equals(e.getClazzName())) {
                    errorList.add("第" + (i + 2) + "行中的班组为空");
                }
                e.setUpdateBy(getUsername());
                e.setUpdateTime(DateUtils.getNowDate());
                e.setCreateTime(DateUtils.getNowDate());
                e.setCreateBy(getUsername());
                //根据身份证获取年龄

            }
            if (errorList.size() > 0) {
                return AjaxResult.error(errorList.toString());
            }

            List<TermWorkerExcel> lst = excelTermWorkers.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(o -> o.getIdCard()))),
                    ArrayList::new));

            if (lst.size() < excelTermWorkers.size()) {
                return AjaxResult.error("身份证信息重复了" + (excelTermWorkers.size() - lst.size()) + "条,请核对");
            }
            errorList.clear();
            errorList = termWorkerService.importTermWorker(excelTermWorkers);
            if (errorList.size() > 0) {
                return AjaxResult.error(errorList.toString());
            }

            return AjaxResult.success("本次成功导入" + excelTermWorkers.size() + "条记录！");
        }*/
    }

    /**
     * 功能描述: 考勤组查询
     *
     * @param
     * @param termAttendanceGroup
     * @return com.ruoyi.common.core.page.TableDataInfo
     * @Date 2021/11/12 10:38
     * @author 刘松山
     */
    @GetMapping("/listTermAttendanceGroup")
    public TableDataInfo listTermAttendanceGroup(TermAttendanceGroup termAttendanceGroup) {
        termAttendanceGroup.setStatus(0);
        List<TermAttendanceGroup> list = termAttendanceGroupService.listTermAttendanceGroup(termAttendanceGroup);
        return getDataTable(list);
    }

    private <T> List<T> baseImport(InputStream inputStream, Integer titleRows, Integer headerRows,
                                   boolean needVerify, Class<T> pojoClass) throws Exception {
        if (inputStream == null) {
            return null;
        } else {
            final ImportParams params = new ImportParams();
            params.setTitleRows(titleRows);
            params.setHeadRows(headerRows);
            params.setNeedVerify(true);
            params.setNeedSave(false);
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        }
    }

    /**
     * 获取职级下拉数组
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author Hush.
     * @since 2021/11/28 16:53
     */
    @GetMapping("/optionProfessionRank")
    public AjaxResult listProfessionRank() {
        return AjaxResult.success(termWorkerService.listProfessionRank());
    }

    /**
     * 导入长期工excel模板
     *
     * @param file:excel模板
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author Hush.
     * @since 2021/12/2 17:37
     */
    @Log(title = "导入长期工excel模板", businessType = BusinessType.IMPORT)
    @PostMapping("/importTermWorker")
    public AjaxResult importTermWorker(MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setVerifyHandler(new TermWorkerExcelVerifyHandlerImpl());
        params.setNeedVerify(true);
        ExcelImportResult<TermWorkerExcel> result = ExcelImportUtil.importExcelMore(file.getInputStream(), TermWorkerExcel.class, params);

        if (result.isVerifyFail()) {
            List<String> fail = result.getFailList().stream().map(mess ->
                            String.format("行号：%s，错误：%s", mess.getRowNum()+1, mess.getErrorMsg()))
                    .collect(Collectors.toList());
            return AjaxResult.error("检测到错误项", fail);
        }
        if (CollectionUtils.isEmpty(result.getList())){
            return AjaxResult.error("未检测到长期工数据信息");
        }
        //检测有无身份证号码重复
        Map<String, List<TermWorkerExcel>> idCardGroup = result.getList().stream().collect(Collectors.groupingBy(TermWorkerExcel::getIdCard));
        for (Map.Entry<String, List<TermWorkerExcel>> entry : idCardGroup.entrySet()) {
            if (entry.getValue().size()>1){
                return AjaxResult.error(String.format("当前excel中存在身份证号重复的数据:%s",entry.getKey()));
            }
        }
        termWorkerService.importTermWorkerTemplate(result.getList());
        return success();
    }

    /**
     * 黑名单员工分页数据
     *
     * @param dto: 检索条件
     * @return com.ruoyi.common.core.page.TableDataInfo
     * @author Hush.
     * @since 2021/12/15 17:16
     */
    @GetMapping("/pageBlockWorker")
    public TableDataInfo pageBlockWorker(RzBlockWorker dto) {
        startPage();
        List<RzBlockWorker> list = termWorkerService.selectRzBlockWorkerList(dto);
        return getDataTable(list);
    }

    @Log(title = "导出黑名单员工信息", businessType = BusinessType.EXPORT)
    @GetMapping("/exportBlockWorker")
    public AjaxResult exportBlockWorker(RzBlockWorker dto) {
        List<RzBlockWorker> list = termWorkerService.selectRzBlockWorkerList(dto);
        ExcelUtil<RzBlockWorker> util = new ExcelUtil<>(RzBlockWorker.class);
        return util.exportExcel(list, "黑名单员工");
    }

    /**
     * 移出黑名单
     *
     * @param beau:员工信息
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author Hush.
     * @since 2021/12/16 15:09
     */
    @Log(title = "移出黑名单", businessType = BusinessType.UPDATE)
    @PostMapping("/removeFromBlacklist")
    public AjaxResult removeFromBlacklist(@RequestBody RzBlockWorker beau) {
        if (StringUtils.isNull(beau.getWorkerType())||StringUtils.isNull(beau.getWorkerId())){
            return error("员工类型或员工ID为空");
        }
        return toAjax(termWorkerService.removeFromBlacklist(beau));
    }

    /**
     * 查询【长期工修改流水】列表
     */

    @GetMapping("/listLog")
    public TableDataInfo listLog(TermWorkerModifyLog termWorkerModifyLog) {
        startPage();
        List<TermWorkerModifyLog>  list = termWorkerService.selectTermWorkerModifyLogById(termWorkerModifyLog);
        return getDataTable(list);
    }
}
